package com.tanhua.sso.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.api.HuanXinApi;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;


    /**
     * 校验用户登录
     *
     * @param phone 手机号
     * @param code  验证码
     * @return token + "|" + isNew
     */
    public String login(String phone, String code) {
        // 校验验证码
        String redisKey = "CHECK_CODE_" + phone;
        if (!StringUtils.equals(code, this.redisTemplate.opsForValue().get(redisKey))) {
            // 校验失败
            return null;
        }

        // 验证码校验完成后需要删除
        this.redisTemplate.delete(redisKey);

        // 判断是否是新用户
        boolean isNew = false;

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        User user = this.userMapper.selectOne(wrapper);
        if (user == null) {
            // 表示是新用户
            // 注册用户信息，并初始化密码
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");

            this.userMapper.insert(user);

            // 注册环信用户
            Boolean register = this.huanXinApi.register(user.getId());
            if (!register) {
                //注册环信失败，记录⽇志
                log.error("注册环信⽤户失败~ userId = " + user.getId());
            }

            isNew = true;
        }


        // 生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，3秒后过期
                .compact();

        try {
            // 发送用户登陆消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("date", System.currentTimeMillis());

            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("消息发送失败！", e);
        }

        return token + "|" + isNew;
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
//            System.out.println(body); //{id=2, exp=1605513392}
            User user = new User();
            // 封装id
            user.setId(Long.valueOf(body.get("id").toString()));

            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            if (this.redisTemplate.hasKey(redisKey)) {
                // redis中有手机号
                String phone = this.redisTemplate.opsForValue().get(redisKey);
                user.setMobile(phone);
                return user;
            }
            //查询数据库
            User u = this.userMapper.selectById(user.getId());
            String phone = u.getMobile();
            user.setMobile(phone);
            //将手机号写入到redis中
            //在jwt中的过期时间的单位为：秒
            long exp = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
            this.redisTemplate.opsForValue().set(redisKey, phone, exp, TimeUnit.MILLISECONDS);

            return user;

        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            log.error("token不合法！token = " + token, e);
        }

        return null;
    }

    /**
     * 更新电话号码
     *
     * @param userId         用户id
     * @param newPhoneNumber 新电话号码
     * @return Boolean
     */
    public Boolean updatePhoneNumber(Long userId, String newPhoneNumber) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId);
        updateWrapper.set("mobile", newPhoneNumber);

        return this.userMapper.update(null, updateWrapper) == 1;
    }

    /**
     * 判断手机号是否已注册
     *
     * @param phoneNumber 手机号
     * @return Boolean
     */
    public Boolean hasNewPhoneNumber(String phoneNumber) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phoneNumber);

        return this.userMapper.selectCount(queryWrapper) == 1;
    }
}
